"use client";

import React, { useState, useRef, useEffect } from 'react';
import { Send, Users, MessageCircle, Settings, X, Edit3 } from 'lucide-react';
import { useChat } from '../hooks/useChat';
import { toast } from 'react-hot-toast';

interface ChatRoomProps {
  isOpen: boolean;
  onToggle: () => void;
}

export function ChatRoom({ isOpen, onToggle }: ChatRoomProps) {
  console.log('[ChatRoom] Component rendering, isOpen:', isOpen);
  
  const {
    connected,
    connecting,
    error,
    messages,
    users,
    currentUser,
    sendMessage,
    changeUsername,
  } = useChat();

  const [messageInput, setMessageInput] = useState('');
  const [showSettings, setShowSettings] = useState(false);
  const [usernameInput, setUsernameInput] = useState(currentUser || '');
  const messagesEndRef = useRef<HTMLDivElement>(null);
  const inputRef = useRef<HTMLInputElement>(null);

  // 自动滚动到最新消息
  useEffect(() => {
    messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' });
  }, [messages]);

  // 当聊天室打开时聚焦输入框
  useEffect(() => {
    if (isOpen && connected) {
      setTimeout(() => inputRef.current?.focus(), 100);
    }
  }, [isOpen, connected]);

  const handleSendMessage = () => {
    if (messageInput.trim() && connected) {
      sendMessage(messageInput);
      setMessageInput('');
    }
  };

  const handleKeyPress = (e: React.KeyboardEvent) => {
    if (e.key === 'Enter' && !e.shiftKey) {
      e.preventDefault();
      handleSendMessage();
    }
  };

  const handleUsernameChange = () => {
    if (usernameInput.trim() && usernameInput !== currentUser) {
      changeUsername(usernameInput.trim());
      setShowSettings(false);
      toast.success('Username updated');
    }
  };

  const formatTime = (timestamp: string) => {
    const date = new Date(timestamp);
    return date.toLocaleTimeString('zh-CN', { 
      hour: '2-digit', 
      minute: '2-digit' 
    });
  };

  if (!isOpen) {
    // 调试：确认组件已渲染但未展开
    if (typeof window !== 'undefined') {
      // 仅在浏览器环境输出
      console.log('[ChatRoom] closed state rendered');
    }
    return (
      <button
        onClick={onToggle}
        className="fixed bottom-6 left-6 z-[200] bg-purple-600 hover:bg-purple-700 text-white p-4 rounded-full shadow-lg transition-all hover:scale-110"
        title="open chat room"
      >
        <MessageCircle size={24} />
        <div className="absolute -top-2 -right-2 w-3 h-3 bg-green-400 rounded-full animate-pulse"></div>
      </button>
    );
  }

  return (
    <div className="fixed top-0 left-0 h-full w-full md:w-80 bg-gray-900 text-white shadow-2xl z-50 flex flex-col">
      {/* Header */}
      <div className="flex justify-between items-center p-4 border-b border-gray-700 bg-gray-800">
        <div className="flex items-center gap-2">
          <MessageCircle size={20} />
          <h2 className="text-lg font-bold">chat room</h2>
          {connected && (
            <span className="flex items-center gap-1 text-sm text-green-400">
              <div className="w-2 h-2 bg-green-400 rounded-full"></div>
              online
            </span>
          )}
        </div>
        <div className="flex items-center gap-2">
          <button
            onClick={() => setShowSettings(!showSettings)}
            className="text-gray-400 hover:text-white transition-colors"
            title="settings"
          >
            <Settings size={20} />
          </button>
          <button
            onClick={onToggle}
            className="text-gray-400 hover:text-white transition-colors"
            title="close chat room"
          >
            <X size={20} />
          </button>
        </div>
      </div>

      {/* Settings Panel */}
      {showSettings && (
        <div className="p-4 bg-gray-800 border-b border-gray-700">
          <div className="space-y-3">
            <div>
              <label className="block text-sm font-medium text-gray-300 mb-1">
                username
              </label>
              <div className="flex gap-2">
                <input
                  type="text"
                  value={usernameInput}
                  onChange={(e) => setUsernameInput(e.target.value)}
                  className="flex-1 bg-gray-700 border border-gray-600 rounded px-3 py-2 text-sm text-white placeholder-gray-400 focus:outline-none focus:ring-2 focus:ring-purple-500"
                  placeholder="input username"
                  maxLength={20}
                />
                <button
                  onClick={handleUsernameChange}
                  className="bg-purple-600 hover:bg-purple-700 text-white px-3 py-2 rounded text-sm transition-colors"
                >
                  <Edit3 size={16} />
                </button>
              </div>
            </div>
          </div>
        </div>
      )}

      {/* Connection Status */}
      {!connected && (
        <div className="p-4 bg-yellow-900 border-b border-yellow-700">
          <div className="flex items-center gap-2 text-yellow-300">
            <div className="w-2 h-2 bg-yellow-400 rounded-full animate-pulse"></div>
            <span className="text-sm">
              {connecting ? 'connecting...' : error ? `connection failed: ${error}` : 'not connected'}
            </span>
          </div>
        </div>
      )}

      {/* Online Users */}
      <div className="p-4 bg-gray-800 border-b border-gray-700">
        <div className="flex items-center gap-2 mb-2">
          <Users size={16} />
          <span className="text-sm font-medium">online users ({users.length})</span>
        </div>
        <div className="flex flex-wrap gap-1">
          {users.map((user) => (
            <span
              key={user.id}
              className={`text-xs px-2 py-1 rounded-full ${
                user.username === currentUser
                  ? 'bg-purple-600 text-white'
                  : 'bg-gray-700 text-gray-300'
              }`}
            >
              {user.username}
            </span>
          ))}
        </div>
      </div>

      {/* Messages */}
      <div className="flex-1 overflow-y-auto p-5 space-y-5">
        {messages.length === 0 ? (
          <div className="text-center text-gray-500 mt-8">
            <MessageCircle size={48} className="mx-auto mb-2 opacity-50" />
            <p>no messages yet</p>
            <p className="text-sm">send your first message to start chatting!</p>
          </div>
        ) : (
          <div className="flex flex-col gap-5">
            {messages.map((message) => {
              const isSelf = message.username === currentUser;
              if (message.isSystem) {
                return (
                  <div key={message.id} className="flex justify-center">
                    <div className="px-4 py-1 text-xs bg-gray-800/60 text-gray-400 rounded-full italic tracking-wide">
                      {message.message}
                    </div>
                  </div>
                );
              }
              return (
                <div
                  key={message.id}
                  className={`flex ${isSelf ? 'justify-end' : 'justify-start'} px-1`}
                >
                  <div
                    className={`relative max-w-[85%] md:max-w-[90%] px-4 py-2 rounded-2xl shadow-sm leading-relaxed break-words whitespace-pre-wrap text-sm border border-transparent ${
                      isSelf
                        ? 'bg-gradient-to-br from-purple-600 to-purple-500 text-white rounded-tr-sm'
                        : 'bg-gray-700 text-gray-100 rounded-tl-sm'
                    }`}
                  >
                    <div className="flex items-center gap-2 mb-1">
                      <span className="text-xs font-medium opacity-80">{message.username}</span>
                      <span className="text-[10px] opacity-50">{formatTime(message.timestamp)}</span>
                    </div>
                    {message.message}
                  </div>
                </div>
              );
            })}
          </div>
        )}
        <div ref={messagesEndRef} />
      </div>

      {/* Message Input */}
      <div className="p-4 border-t border-gray-700">
        <div className="flex gap-2">
          <input
            ref={inputRef}
            type="text"
            value={messageInput}
            onChange={(e) => setMessageInput(e.target.value)}
            onKeyPress={handleKeyPress}
            disabled={!connected}
            className="flex-1 bg-gray-800 border border-gray-600 rounded-lg px-3 py-2 text-white placeholder-gray-400 focus:outline-none focus:ring-2 focus:ring-purple-500 disabled:opacity-50"
            placeholder={connected ? "input message..." : "connecting..."}
            maxLength={500}
          />
          <button
            onClick={handleSendMessage}
            disabled={!connected || !messageInput.trim()}
            className="bg-purple-600 hover:bg-purple-700 disabled:opacity-50 disabled:cursor-not-allowed text-white p-2 rounded-lg transition-colors"
          >
            <Send size={20} />
          </button>
        </div>
        {messageInput.length > 0 && (
          <div className="text-xs text-gray-500 mt-1 text-right">
            {messageInput.length}/500
          </div>
        )}
      </div>
    </div>
  );
}
